package org.raymond.iworks.study.redis.redisson;

import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;

/**
 * @author raymond
 * @version V1.0
 * @Description: TODO
 */
@Slf4j
public class SemaphoreTest {
    public static void main(String[] args) throws InterruptedException {
        test();
    }

    public static void test() throws InterruptedException {
        RedissonClient client = client();
        RSemaphore semaphore = client.getSemaphore("mySemaphore");
        semaphore.addPermits(1);
        for(int i=0; i<10; i++){
            final int j = i;
            new Thread(()->{
                try {
                    log.info("尝试获取资源 {}", j);
                    semaphore.acquire();
                    log.info("得到资源 {}", j);
                    Thread.sleep(1000*1);
                } catch (InterruptedException e) {
                } finally {
                    log.info("释放资源 {}", j);
                    semaphore.release();
                }
            }).start();
        }

        Thread.sleep(20_000);

        semaphore.delete();
        client.shutdown();
    }

    public static RedissonClient client(){
        Config cfg = new Config();
        cfg.useSingleServer().setAddress("redis://192.168.0.125:6379");
        RedissonClient client = Redisson.create(cfg);
        return client;
    }
}
